package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;

	@Autowired
	private RSAAutoCertificateConfig config;

	@Autowired
	private OrderInfoFeignClient orderInfoFeignClient;

	@Autowired
	private WxPayV3Config wxPayV3Config;

	@Autowired
	private UserInfoFeignClient userInfoFeignClient;

	@Override
	public Transaction wxNotify(HttpServletRequest request) {
		//	从请求头中获取构建requestParam 对象的参数
		String wechatPaySerial = request.getHeader("Wechatpay-Serial");
		String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
		String wechatSignature = request.getHeader("Wechatpay-Signature");
		String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
		String requestBody = PayUtil.readData(request);

		// 构造 RequestParam
		RequestParam requestParam = new RequestParam.Builder()
				.serialNumber(wechatPaySerial)
				.nonce(wechatpayNonce)
				.signature(wechatSignature)
				.timestamp(wechatTimestamp)
				.body(requestBody)
				.build();

		// 初始化 NotificationParser
		NotificationParser parser = new NotificationParser(config);
		Transaction transaction = null;
		try {
			// 以支付通知回调为例，验签、解密并转换成 Transaction
			transaction = parser.parse(requestParam, Transaction.class);

		} catch (ValidationException e) {
			// 签名验证失败，返回 401 UNAUTHORIZED 状态码
			log.error("sign verification failed", e);
			throw  new GuiguException(ResultCodeEnum.UNAUTHORIZED);
		}

		// 200 OK
		if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
			//	返回数据对象
			return transaction;
		} else {
			//	如果处理失败，应返回 4xx/5xx 的状态码，例如 500 INTERNAL_SERVER_ERROR
			throw new GuiguException(ResultCodeEnum.INTERNAL_SERVER_ERROR);
		}

	}

	@Override
	public Transaction queryPayStatus(String orderNo) {
		//	ById --> ByOutTradeNo
		//	创建一个config对象。
		//	创建服务对象
		JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
		//	声明订单号查询对象
		QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
		//	商户订单号
		request.setOutTradeNo(orderNo);
		request.setMchid(wxPayV3Config.merchantId);

		try {
			//	根据订单号查询对象。
			Transaction result = service.queryOrderByOutTradeNo(request);
			System.out.println(result.getTradeState());
			//	返回数据
			return result;
		} catch (ServiceException e) {
			// API返回失败, 例如ORDER_NOT_EXISTS
			System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
			System.out.printf("reponse body=[%s]\n", e.getResponseBody());
		}
		return null;
	}

	@Override
	public Map<String, Object> createJsapi(String paymentType, String orderNo, Long userId) {
		//	创建一个map 集合
		HashMap<String, Object> result = new HashMap<>();
		//	在支付之前判断当前这个订单的交易状态. key = orderNo value = 1  setnx key value 开发退款功能！
		//	微信用于订单支付的时候，才会查询订单对象。 如果微信用于充值业务不需要查询订单对象。
		if (paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)){ // 微信用于订单支付
			//	获取到订单对象.
			Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfo(orderNo);
			Assert.notNull(orderInfoResult,"订单结果集为空");
			OrderInfo orderInfo = orderInfoResult.getData();
			Assert.notNull(orderInfo,"订单为空");
			//	判断订单的状态. 订单状态是已取消或已支付
			if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus())
					|| SystemConstant.ORDER_STATUS_PAID.equals(orderInfo.getOrderStatus())){
				//	返回
				return result;
			}
		}
		//	现在想把交易记录与充值记录都放入paymentInfo！
		//	保存交易记录： insert into payment_info
		paymentInfoService.savePaymentInfo(orderNo,paymentType);

		//	创建一个config对象。
		//	创建服务对象
		JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();

		// 跟之前下单示例一样，填充预下单参数
		PrepayRequest request = new PrepayRequest();
		Amount amount = new Amount();
		//	orderInfo.getOrderAmount().intValue() 23.98 元--->分
		//	给固定值
		amount.setTotal(1);
		request.setAmount(amount);
		request.setAppid(wxPayV3Config.getAppid());
		request.setMchid(wxPayV3Config.merchantId);
		request.setDescription("测试商品标题");
		request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
		//	request.setTimeExpire(); 绝对超时时间。
		//	订单号
		request.setOutTradeNo(orderNo);
		Payer payer = new Payer();
		//	获取openId
		Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
		Assert.notNull(userInfoVoResult,"用户返回结果集为空");
		UserInfoVo userInfoVo = userInfoVoResult.getData();
		Assert.notNull(userInfoVo,"用户对象为空");
		payer.setOpenid(userInfoVo.getWxOpenId());
		request.setPayer(payer);
		// response包含了调起支付所需的所有参数，可直接用于前端调起支付
		PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
		//	赋值操作：
		result.put("timeStamp", response.getTimeStamp()); // 时间戳
		result.put("nonceStr", response.getNonceStr());   // 随机字符串
		result.put("package", response.getPackageVal());  // 订单详情扩展字符串
		result.put("signType", response.getSignType());   // 签名方式
		result.put("paySign", response.getPaySign());     // 签名
		//	返回map 数据
		return result;
	}
}
